Incorrect Monitor Usage (IMU)

Description:

Wait or Pulse operations on a monitor can be performed only if the thread has locked this monitor. In case of a Wait operation, this lock is released, and the thread is suspended until the object will be signaled. However, if the thread has locked more than one monitor, then only one lock will be released and the other monitors are kept locked by the waiting thread. It can be intended behavior, but in most cases, it means that there is a bug in the program design because resources usually are locked for a short time to increase program parallelism and avoid deadlocks.

IMU can produce the following messages:

  1. Target of Wait or Pulse is not locked within method body
  2. Method Wait or Pulse is invoked without locking any monitor
  3. Method Wait is invoked with more than one monitor locked

The first message is produced when a monitor is accessed in a non-synchronized method and outside of any synchronized construction. The second message is more selective because it is based on resource lock analysis. It checks that there is such an execution path from the thread entry point on which the monitor can be accessed without a lock.

Incorrect:

public class Registry { 
    public void Register(object key, object value) { 
        ...
        Monitor.PulseAll(this);
        ...
    }
}

Correct:

public class Registry { 
    public void Register(object key, object value) { 
        lock (this) 
        { 
            ...
            Monitor.PulseAll(this);
            ...
        }
    }
}